﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using LitJson;

[AddComponentMenu("PUEX/Affector/Size/DimensionsBySpeed")]
public class PUEXDimensionsBySpeedAffector : PUEXAffector {

	#region - Editable property
	public PUEXDynamicAttribute dimensionsXBySpeed;
	public PUEXDynamicAttribute dimensionsYBySpeed;
	public PUEXDynamicAttribute dimensionsZBySpeed;
	public float speedRangeMin;
	public float speedRangeMax;
	#endregion
	
	#region - Lifecycle
	public PUEXDimensionsBySpeedAffector ()
	{
		dimensionsXBySpeed = PUEXDynamicAttribute.GenerateFixed (1f);
		dimensionsYBySpeed = PUEXDynamicAttribute.GenerateFixed (1f);
		dimensionsZBySpeed = PUEXDynamicAttribute.GenerateFixed (1f);
		speedRangeMin = 0f;
		speedRangeMax = 1f;
	}

	public override void enable () {
		if (speedRangeMin > speedRangeMax) {
			float tmp = speedRangeMin;
			speedRangeMin = speedRangeMax;
			speedRangeMax = tmp;
		}
		
		base.enable ();
	}
	#endregion
	
	#region - Update
	public override void update (float dt, PUEXParticle particle)
	{
		float t = 0f;
		float absSpeed = Mathf.Abs (particle.speed);
		if (absSpeed < speedRangeMin) {
			t = 0f;
		} else if (absSpeed > speedRangeMax) {
			t = 1f;
		} else {
			t = (absSpeed - speedRangeMin) / (speedRangeMax - speedRangeMin);
		}

		particle.setDimensions (Vector3.Scale(particle.originalDimensions(), new Vector3(dimensionsXBySpeed.getValue(t), dimensionsYBySpeed.getValue(t), dimensionsZBySpeed.getValue(t))));
	}
	#endregion

	#region - Param property
	public override void updateParams (PUEXParticleSystem system)
	{
		dimensionsXBySpeed.parameterize (system);
		dimensionsYBySpeed.parameterize (system);
		dimensionsZBySpeed.parameterize (system);
	}
	#endregion

	#region - Serialization
	public override JsonData save (JsonData emitterData, JsonData systemData)
	{
		JsonData ret = base.save (emitterData, systemData);

		ret ["dimensions_x_by_speed"] = PUEXUtils.serializeDynamicAttribute(dimensionsXBySpeed);
		ret ["dimensions_y_by_speed"] = PUEXUtils.serializeDynamicAttribute(dimensionsYBySpeed);
		ret ["dimensions_z_by_speed"] = PUEXUtils.serializeDynamicAttribute(dimensionsZBySpeed);
		ret ["speed_range_min"] = speedRangeMin;
		ret ["speed_range_max"] = speedRangeMax;
		
		return ret;
	}
	#endregion

}
